_ = require 'underscore'

# 对象遍历 - 深度遍历
iterateObject = (obj, path, callback) ->
  if typeof path == 'function'
    callback = path
    path = null
  _.forEach obj, (value, key) ->
    currentPath = undefined
    if _.isArray(obj)
      currentPath = path + '[' + key + ']'
    else
      currentPath = if path then path + '.' + key else key
    if value and _.isArray(value)
      _.forEach value, (item, index) ->
        tempPath = currentPath + '[' + index + ']'
        if !_.isObject(item) and !_.isArray(item)
          return callback(index, tempPath, item)
        iterateObject item, tempPath, callback
    else if value and _.isObject(value)
      return iterateObject(value, currentPath, callback)
    else
      return callback(key, currentPath, value)
    return
  return

# 对象深度遍历
deepMap = (obj, callback, path) ->
  results = []
  _.forEach obj, (value, key) ->
    currentPath = undefined
    if _.isArray(obj)
      currentPath = path + '[' + key + ']'
    else
      currentPath = if path then path + '.' + key else key
    if value and _.isArray(value)
      _.forEach value, (item, index) ->
        tempPath = currentPath + '[' + index + ']'
        if !_.isObject(item) and !_.isArray(item)
          results.push callback(index, tempPath, item)
        else
          results = results.concat(deepMap(item, callback, tempPath))
        return
    else if value and _.isObject(value)
      results = results.concat(deepMap(value, callback, currentPath))
    else
      results.push callback(key, currentPath, value)
    return

  results = _.compact(results)
  results

module.exports =
  iterateObject: iterateObject
  deepMap: deepMap